package com.st.mall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.additional.query.impl.LambdaQueryChainWrapper;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.st.common.utils.PageUtils;
import com.st.common.utils.Query;

import com.st.mall.product.dao.ProductAttrValueDao;
import com.st.mall.product.entity.ProductAttrValueEntity;
import com.st.mall.product.service.ProductAttrValueService;
import org.springframework.transaction.annotation.Transactional;


@Service("productAttrValueService")
public class ProductAttrValueServiceImpl extends ServiceImpl<ProductAttrValueDao, ProductAttrValueEntity> implements ProductAttrValueService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<ProductAttrValueEntity> page = this.page(
                new Query<ProductAttrValueEntity>().getPage(params),
                new QueryWrapper<ProductAttrValueEntity>()
        );

        return new PageUtils(page);
    }
    @Override
    public void saveProductAttr(List<ProductAttrValueEntity> collect) {
        this.saveBatch(collect);
    }

    @Override
    public List<ProductAttrValueEntity> getAttrBySpuId(Long spuI) {
        QueryWrapper<ProductAttrValueEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("spu_id", spuI);
        return this.list(wrapper);
    }

    @Transactional
    @Override
    public   void updateBySpuId(Long spuId, List<ProductAttrValueEntity> attrs){
        //先删除旧的规格
        this.baseMapper.delete(new LambdaQueryWrapper<ProductAttrValueEntity>().eq(ProductAttrValueEntity::getSpuId,spuId));
        //再插入新的规格
        if(attrs!=null&&attrs.size()>0){
            List<ProductAttrValueEntity> collect = attrs.stream().map(attr -> {
                attr.setSpuId(spuId);
                return attr;
            }).collect(Collectors.toList());
            this.saveBatch(collect);
        }
    }

}